import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_module/commom/application.dart';
import 'package:flutter_module/event/connect_mqtt_event.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:flutter_module/beans/Entity.dart';
import 'package:flutter_module/mqtt/Mqtt.dart';
import 'package:better_socket/better_socket.dart';
import '../../DemoLocalizations.dart';
import 'machine_settings.dart';
import 'machine_switch.dart';

class TestDemo extends StatefulWidget {

  final App_esp_ip model;

  const TestDemo({Key key, this.model}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _TestDemoState();
  }
}

class _TestDemoState extends State<TestDemo>
    with SingleTickerProviderStateMixin {
  TabController mController;
  List<String> tabTitles;
  Mqtt demo ;
  Timer t;
  var errorTime = 0;
  var _colorSubscription;
  @override
  Widget build(BuildContext context) {
    tabTitles = [
      DemoLocalizations.of(context).ParameterSettings,
      DemoLocalizations.of(context).Switchcontrol,
    ];
    return Scaffold(
      appBar: _appBarView(),
      body: _tabBarView(),
    );
  }

  @override
  void dispose() {
    super.dispose();
    mController.dispose();
    BetterSocket.close();
    demo.disconnect();
    _colorSubscription.cancel();
    if(t!=null){
      if(t!=null){
        t.cancel();
      }
    }
  }

  @override
  void initState() {
    super.initState();
    print(widget.model);
    bool result = Mqtt.setInstance(widget.model);
    demo = Mqtt.getInstance();
    demo.connect();

    tabTitles = [
      '参数设置',
      '开关控制',
    ];

    mController = TabController(
      length: tabTitles.length,
      vsync: this,
    );

    //订阅eventbus
    _colorSubscription = Application.eventBus.on<ConnectMqttEvent>().listen((event) {
      this.registerGetState();
    });
  }

  void registerGetState() {
    lookState();
    t = Timer.periodic(Duration(minutes: 1), (timer) {
      getState();
      print("registerGetState start");
    });
  }

  void lookState(){
    errorTime++;
    Future.delayed(Duration(seconds: 1), (){
      getState();
    });
  }
  void getState(){
    if(errorTime>2){
      print("errorTime>3");
      errorTime = 0;
      return;
    }
//    print("执行了一次");

    final MqttClientPayloadBuilder builder = MqttClientPayloadBuilder();
    builder.addByte(0x48);
    builder.addByte(0x4F);
    builder.addByte(0x47);
    builder.addByte(0x52);
    builder.addByte(0x44);
    demo.publishMessageWithResponse(builder,(String error){
      if (error == "connecting") {
        Future.delayed(Duration(seconds: 1), (){
          lookState();
        });
      }else{
        lookState();
      }
    });
  }

  Widget _appBarView() {
//    print("模式"+widget.model.espType);
    if(widget.model.espType=="41"||widget.model.espType=="42"||widget.model.espType=="43"){
      return AppBar(
        centerTitle: true,
        title: Text(DemoLocalizations.of(context).PowerSettings),
      );
    }
    if (widget.model.share) {
      if (widget.model.level == 0) {
        return AppBar(
          centerTitle: true,
          title: Text(DemoLocalizations.of(context).Switchcontrol),
        );
      }
    }
    return AppBar(
      centerTitle: true,
      title: _tabBar(),
    );
  }

  Widget _tabBar() {
    return TabBar(
        //设置tab是否可水平滑动
        isScrollable: true,
        //控制器
        controller: mController,
        //设置tab文字得类型
        labelStyle: TextStyle(fontSize: 17, fontWeight: FontWeight.bold),
        //设置tab选中得颜色
        labelColor: Colors.black,
        //设置tab未选中得颜色
        unselectedLabelColor: Colors.black45,
        //设置自定义tab的指示器，CustomUnderlineTabIndicator
        //若不需要自定义，可直接通过
        //indicatorColor 设置指示器颜色
        //indicatorWight 设置指示器厚度
        //indicatorPadding
        //indicatorSize  设置指示器大小计算方式
//        indicator: CustomUnderlineTabIndicator(
//            strokeCap: StrokeCap.round,
//            insets: EdgeInsets.only(left: 15, right: 15),
//            borderSide: BorderSide(width: 4.0, color: Colors.red)),
        tabs: tabTitles.map((item) {
          return Tab(text: item);
        }).toList());
  }

  Widget _tabBarView() {
    if(widget.model.espType=="41"||widget.model.espType=="42"||widget.model.espType=="43"){
      return new VideoBookMusicBookWidget( model: widget.model,);
    }
//    print("模式"+widget.model.espType);
    if (widget.model.share) {
      if (widget.model.level == 0) {
        return new VideoBookMusicBookWidget(model: widget.model,);
      }
    }
    return TabBarView(
      controller: mController,
      children: tabTitles.map((item) {
        if(item == DemoLocalizations.of(context).ParameterSettings){
          return new MachineSettings(model: widget.model,);
        }else{
          return new VideoBookMusicBookWidget(model: widget.model,);
        }
      }).toList(),
    );
  }
}